﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mortgage.DAL.Entity;
using Mortgage.DAL;
using Mortgage.Srv.Cls;

namespace Mortgage.Srv
{
    public interface IMortgageSrv
    {
        List<tMortgage> GetAll(int ageId);
        tMortgage GetById(int id);
        int Insert(tMortgage insObj);
        int Update(tMortgage newsObj);
        int Delete(tMortgage delObje);
        int ChangeStatus(tMortgage obj, int status);
        List<vwMortgageInfo> Find(int agentid, string serialNo, DateTime? dteMorgate, DateTime? dteMorgateEnd, string customerName, string itemName, int? status, int pageSize, int pageIdx, out int totalCal);
        List<vwMortgageInfo> FilterMortgageExpire(DateTime dte, int agentid);
        int BulkExpired(List<long> ids);
    }

    class MortgageSrv : IMortgageSrv
    {
        private MortgageDataContext dataContext;

        public MortgageSrv()
        {
            dataContext = new MortgageDataContext();

        }

        public List<tMortgage> GetAll(int ageId)
        {
            List<tMortgage> result;
            result = dataContext.tMortgages.Where(m => m.Age_ID == ageId && m.IsDelete == false).OrderByDescending(m => m.ModifiedDate).ToList();
            return result;
        }

        public tMortgage GetById(int id)
        {
            tMortgage result = dataContext.tMortgages.Where(a => a.ID == id).FirstOrDefault();
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="insObj"></param>
        /// <returns>
        /// 0: success
        /// 2: Serial No dupliacte
        /// other: error code
        /// </returns>
        public int Insert(tMortgage insObj)
        {
            insObj.Status = (int)Cls.EnmMortgageStatus.New;
            if (dataContext.tMortgages.Any(m => m.IsDelete == false && m.SerialNo == insObj.SerialNo))
                return 2;


            dataContext.tMortgages.InsertOnSubmit(insObj);
            dataContext.SubmitChanges();
            return 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="newsObj"></param>
        /// <returns>
        /// 0: success
        /// 1: No find update object
        /// 2: Begin date not valid
        /// other: error code
        /// </returns>
        public int Update(tMortgage newsObj)
        {
            if (!dataContext.tMortgages.Any(m => m.ID == newsObj.ID))
                return 1;
            if (dataContext.tMortgages.Any(m => m.IsDelete == false && m.SerialNo == newsObj.SerialNo && m.ID != newsObj.ID))
                return 2;


            //Begin date can not update
            tMortgage entity = dataContext.tMortgages.Where(a => a.ID == newsObj.ID).FirstOrDefault();
            if (entity == null) return 1;
            // Passs date

            entity.Age_ID = newsObj.Age_ID;
            entity.CustomerAddress = newsObj.CustomerAddress;
            entity.CustomerName = newsObj.CustomerName;
            entity.CustomerPhone = newsObj.CustomerPhone;
            entity.EnmInterestRateType = newsObj.EnmInterestRateType;

            entity.Inter_ID = newsObj.Inter_ID;
            entity.InterestRate = newsObj.InterestRate;
            entity.ItemDescription = newsObj.ItemDescription;
            entity.ItemName = newsObj.ItemName;
            entity.MorDate = newsObj.MorDate;
            entity.MorMoney = newsObj.MorMoney;


            entity.ModifiedBy = newsObj.ModifiedBy;
            entity.ModifiedDate = newsObj.ModifiedDate;


            dataContext.SubmitChanges();
            return 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="delObje"></param>
        /// <returns>
        /// 0: succcessful
        /// 1: No find delete object
        /// other: error code
        /// </returns>
        public int Delete(tMortgage delObje)
        {
            tMortgage entity = dataContext.tMortgages.Where(a => a.ID == delObje.ID).FirstOrDefault();
            if (entity == null) return 1;

            entity.IsDelete = true;
            entity.ModifiedBy = delObje.ModifiedBy;
            entity.ModifiedDate = delObje.ModifiedDate;


            dataContext.SubmitChanges();

            return 0;
        }

        public List<vwMortgageInfo> Find(int agentId, string serialNo, DateTime? dteMorgate, DateTime? dteMorgateEnd, string customerName, string itemName, int? status, int pageSize, int pageIdx, out int totalCal)
        {
            List<vwMortgageInfo> filterResult = (from vw in dataContext.vwMortgageInfos
                                                 where (string.IsNullOrEmpty(serialNo) || vw.SerialNo == serialNo)
                                                 && vw.Age_ID == agentId
                                                 && (dteMorgate == null || (dteMorgate != null ? vw.MorDate.GetValueOrDefault().Date >= dteMorgate.GetValueOrDefault().Date : true))
                                                 && (dteMorgateEnd == null || (dteMorgateEnd != null ? vw.MorDate.GetValueOrDefault().Date <= dteMorgateEnd.GetValueOrDefault().Date : true))
                                                 && (string.IsNullOrEmpty(customerName) || vw.CustomerName.Contains(customerName))
                                                 && (string.IsNullOrEmpty(itemName) || vw.ItemName.Contains(itemName))
                                                 && (status == null || vw.Status == status.GetValueOrDefault())

                                                 orderby vw.ModifiedDate descending
                                                 select vw).ToList();

            totalCal = filterResult.Count;
            List<vwMortgageInfo> result = filterResult.Skip(pageSize * pageIdx).Take(pageSize).ToList();

            return result;
        }

        public List<vwMortgageInfo> FilterMortgageExpire(DateTime dte, int agentid)
        {

            List<vwMortgageInfo> filterResult = (from vw in dataContext.vwMortgageInfos
                                                 where (vw.Status != (int)EnmMortgageStatus.Expired && vw.Status != (int)EnmMortgageStatus.Done) // On mortage 
                                                 //&& !(vw.BillDate.GetValueOrDefault(vw.MorDate.GetValueOrDefault()).AddDays(vw.NumDayExpire.GetValueOrDefault()) > dte)
                                                 && !(vw.CurMorDate.GetValueOrDefault().AddDays(vw.NumDayExpire.GetValueOrDefault()) > dte)
                                                 && vw.Age_ID == agentid
                                                 orderby vw.ModifiedDate descending
                                                 select vw).ToList();
            return filterResult;
        }

        public vwMortgageInfo GetByMortgageId(int id)
        {
            vwMortgageInfo result = dataContext.vwMortgageInfos.Where(m => m.ID == id).FirstOrDefault();
            return result;
        }

        public int ChangeStatus(tMortgage obj, int status)
        {
            int result = 0;
            tMortgage morObj = dataContext.tMortgages.Where(m => m.ID == obj.ID).FirstOrDefault();
            if (morObj != null)
            {
                morObj.Status = status;
                dataContext.SubmitChanges();
            }
            else
                result = 1;
            return result;
        }

        public int BulkExpired(List<long> ids)
        {
            int result = 0;
            
            dataContext.tMortgages.Where(m => ids.Contains(m.ID)).ToList().ForEach(m => m.Status = (int)EnmMortgageStatus.Expired);
            dataContext.SubmitChanges();
            return result;

        }
    }
}
